package es.code.xatransaction.persistence.hibernate;

import java.util.List;

import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import es.code.xatransaction.model.Pojo;
import es.code.xatransaction.persistence.MessageSequenceDAO;

public class MessageSequenceHibernateDAO extends HibernateDaoSupport 
	implements MessageSequenceDAO {

	public int insertSequence(String app, String appKey, int value) {
		Pojo pojo = new Pojo();
		pojo.setAppKey(appKey);
		pojo.setAppName(app);
		pojo.setValue(Integer.toString(value));
		getHibernateTemplate().saveOrUpdate(pojo);
		return 0;
	}

	public int selectSequence(String app, String appKey) {
		Object[] params = new Object[2];
		params[0] = app;
		params[1] = appKey;
		List<Pojo> res = getHibernateTemplate().find("select p from Pojo p where p.appName = ? and p.appKey = ? ", params);
		Pojo p = (Pojo)res.get(0);
		return Integer.parseInt(p.getValue());
	}

	public int updateSequence(int seqNum, String application, String serverName) {
		Object[] params = new Object[3];
		params[0] = Integer.toString(seqNum);
		params[1] = application;
		params[2] = serverName;
		try {
			getHibernateTemplate().bulkUpdate("update Pojo p set p.value = ? where p.appName = ? and p.appKey = ? ", params);
			return 0;
		} catch (DataAccessException e) {
			e.printStackTrace();
			return -1;
		}
	}

}
